package com.gopay.cron.web.controller;

import com.gopay.common.domain.acps.AcctProd;
import com.gopay.common.domain.acps.model.AcctMastBean;
import com.gopay.cron.service.cloud.CloudAccountGenFtpFileService;
import com.gopay.cron.service.cloud.CloudAccountStatementGenService;
import com.gopay.remote.acps.service.AcctTransRemoteService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Johnson on 2017/3/1.
 */
@Controller
public class CloudOrderFileGenController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource(name = "cloudAccountStatementGenService")
    private CloudAccountStatementGenService cloudAccountStatementGenService;

    @Resource(name = "acctTransRemoteService")
    private AcctTransRemoteService acctTransRemoteService;

    @Value("#{webProperties['cloud.statementOfAccountGen.basePath']}")
    private String basePath;

    @Value("#{webProperties['cloud.accountGenFtp.custIds']}")
    private String custIdsFtp;

    @Value("#{webProperties['cloud.accountGenFtp.basePath']}")
    private String basePathFtp;

    @Resource(name = "cloudAccountGenFtpFileService")
    private CloudAccountGenFtpFileService cloudAccountGenFtpFileService;

    //@RequestMapping("/cloud/index")
    public void index() throws Exception {
        long begin = System.currentTimeMillis();
        logger.error("++++++++云账户生成对账文件开始++++++++");

        String checkDate = getRequest().getParameter("checkDate");
        String custId = getRequest().getParameter("custId");
        String acctId = getRequest().getParameter("acctId");

        try {
            AcctMastBean bean = acctTransRemoteService.getAccount(acctId);
            cloudAccountStatementGenService.genFile(basePath,checkDate,custId,acctId,bean.getProdCodeStr());
        } catch (Exception e) {
            logger.error("生成失败",e);
        }

        long end = System.currentTimeMillis();
        logger.error("++++++++云账户生成对账文件结束++++++++end:"+(end-begin));
    }

    /*@RequestMapping("/cloud/clean")
    public void clean() {
        String custIds = getRequest().getParameter("custIds");
        cloudAccountStatementGenService.cleanYesterdayFileDownloadNum(getPlatformCustIds(custIds));
    }

    private Set<String> getPlatformCustIds(String custIds) {
        Set<String> set = new HashSet<>();
        if(custIds != null && !"".equals(custIds)) {
            if(custIds.contains(",")) {
                String[] strArr = custIds.split(",");
                for(int i = 0; i < strArr.length; i++) {
                    set.add(strArr[i]);
                }
            } else {
                set.add(custIds);
            }
        }
        return set;
    }*/

    private HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }

    @RequestMapping("/cloud/uploadFtp")
    public String uploadFtp() throws Exception {
        logger.info("++++++++云账户生成对账文件开始++++++++:");
        long begin = System.currentTimeMillis();

        String checkDate = getRequest().getParameter("checkDate");
        if(StringUtils.isBlank(checkDate)){
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE,-1);
            checkDate= new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        }
        Set<String> custIdSet = getCustIds(getRequest().getParameter("custId"));
        String acctId = getRequest().getParameter("acctId");

        try {
            for(String custId : custIdSet) {
                List<AcctMastBean> accts = new ArrayList<>();

                if(StringUtils.isBlank(acctId)){
                    accts = acctTransRemoteService.getAccounts(custId);
                }else{
                    AcctMastBean bean = acctTransRemoteService.getAccount(acctId);
                    accts.add(bean);
                }

                for(AcctMastBean acct : accts) {
                    //1.生成本地文件及上传FTP(普通账户才生成)
                    if(AcctProd.GNST.toString().equals(acct.getProdCodeStr())) {
                        logger.info("custId:"+custId+",acctId:"+acct.getAcctId()+",acctProd:"+acct.getProdCodeStr());
                        cloudAccountGenFtpFileService.genFile(basePathFtp,checkDate,custId,acct.getAcctId(),acct.getProdCodeStr());
                    }
                }
            }
        } catch (Exception e) {
            logger.error("生成失败",e);
            throw e;
        }
        long end = System.currentTimeMillis();
        logger.info("++++++++云账户生成对账文件结束++++++++end:"+(end-begin));
        return "index";
    }

    private Set<String> getCustIds(String custId) {
        Set<String> set = new HashSet<>();
        if(StringUtils.isBlank(custId)){
            if(this.custIdsFtp != null && StringUtils.isNotBlank(this.custIdsFtp)) {
                if(this.custIdsFtp.contains(",")) {
                    String[] strArr = this.custIdsFtp.split(",");
                    for(int i = 0; i < strArr.length; i++) {
                        set.add(strArr[i]);
                    }
                } else {
                    set.add(this.custIdsFtp);
                }
            }
        }else{
            set.add(custId);
        }
        return set;
    }

}
